/*
 * @Description: 权限规则 - 用户列表 - 列表组件
 * @Author: Rfan
 * @Date: 2022-04-08 09:07:14
 * @LastEditTime: 2022-05-25 09:02:08
 */

import { useMemo, useState } from 'react';
import { Button, Table, Tag } from 'antd';
import classNames from 'classnames/bind';
import type { FC, Key, MouseEvent } from 'react';
import { useUseRuleContext } from '../../contexts/UseRuleContext';
import { useFormatMessage } from '@/utils/intlHelpers';
import RuleSettingDialog from '../dialogs/RuleSettingDialog';

import styles from '../../styles/list.module.scss';

const cx = classNames.bind(styles);

export type UserTableProps = {
  title?: string;
  data?: any;
};

const columns: any[] = [
  {
    title: '序号',
    dataIndex: 'entryId',
    key: 'entryId',
    align: 'center'
  },
  {
    title: '用户或组名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center'
  }
];

const UserTable: FC<UserTableProps> = () => {
  console.log('UserTable:');
  const { userSelectItems, userList, userTableTitles, setUserSelectItems, getUserRights } =
    useUseRuleContext();
  const formatMessage = useFormatMessage();
  // 添加规则弹窗状态
  const [ruleSettingVisible, setRuleSettingVisible] = useState(false);

  /**
   * @description 将返回的动态数据数组整合到数据中
   * @param {*} userList 返回的用户列表，包含类型为数组的动态数据
   * @return {*} 合并后的新数据
   * @example
   * // input
   *{ id:1, name: 'zhangsan',list:[{name:'download',index:1,value:1}] }
   * // output
   *{ id:1, name: 'zhangsan',1:{name:'download',index:1,value:1} }
   */
  const formatData = userList.map((item: any) => {
    const obj: any = {};
    // 将数组转换为对象合并到所在的对象中
    for (let i = 0; i < item.operateRightsList.length; i++) {
      const ele = item.operateRightsList[i];
      obj[ele.index] = ele;
    }
    return { ...item, ...obj };
  });

  // 操作列
  const operateCol = {
    title: formatMessage('tableAction'),
    key: 'action',
    align: 'center',
    render: (record: any) => (
      <Button
        type="link"
        onClick={(evt) => {
          showEditDialog(evt, record.entryId);
        }}
      >
        操作
      </Button>
    )
  };

  /**
   * @description: 表单列，讲固定列与动态列合并
   * @param {*} columns 固定列
   * @param {*} userTableTitles 动态列
   * @return {*} 合并后的列
   */
  const cols = columns.concat(
    userTableTitles.map((item: any) => {
      return {
        title: item.name,
        dataIndex: item.index,
        key: item.index,
        align: 'center',
        render: (tag: any) => (
          <Tag color={tag.value === 1 ? 'blue' : 'red'}>{tag.name.toUpperCase()}</Tag>
        )
      };
    }),
    operateCol
  );

  /**
   * @description: 表格选中相关
   * @param {number} selectedKeys
   * @return {*}
   */
  const onSelectChange = (selectedKeys: number[]): void => {
    console.log('onSelectChange', selectedKeys);

    setUserSelectItems(selectedKeys);
  };

  /**
   * @description: 表格增加复选框相关参数
   */
  const rowSelection: any = {
    selectedRowKeys: userSelectItems,
    onChange: onSelectChange
  };

  /**
   * @description: 表格选中条目方法
   * @param {any} record 选中的条目
   */
  const selectRow = (record: any) => {
    const _userSelectItems = [...userSelectItems];
    const selectIdx = _userSelectItems.indexOf(record.entryId);
    if (selectIdx < 0) {
      setUserSelectItems([...userSelectItems, record.entryId]);
    } else {
      _userSelectItems.splice(selectIdx, 1);
      setUserSelectItems(_userSelectItems);
    }
  };

  /**
   * @description: 关闭添加规则弹窗，根据参数判断取消还是保存
   */
  const showEditDialog = (evt: MouseEvent, id: Key) => {
    evt.stopPropagation();
    getUserRights(id).then(() => {
      setRuleSettingVisible(true);
    });
  };

  /**
   * @description: 关闭添加规则弹窗，根据参数判断取消还是保存
   */
  const closeEditDialog = () => {
    setRuleSettingVisible(false);
  };

  return (
    <div className={cx('approve-list')}>
      <Table
        dataSource={formatData}
        columns={cols}
        rowKey="entryId"
        size="small"
        rowSelection={rowSelection}
        pagination={false}
        bordered
        onRow={(record) => ({
          onClick: () => {
            selectRow(record);
          }
        })}
      />
      {useMemo(
        () => (
          <RuleSettingDialog visible={ruleSettingVisible} onClose={closeEditDialog} />
        ),
        [ruleSettingVisible]
      )}
    </div>
  );
};

export default UserTable;
